package cn.wolfcode.crm.web.interceptor;

import cn.wolfcode.crm.domain.Employee;
import cn.wolfcode.crm.util.UserContext;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

public class PermissionInterceptor extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1 通过判断employee的admin是否超管,是的话放行
        //Employee employee = (Employee) request.getSession().getAttribute("EMPLOYEE_IN_SESSION");
        Employee employee = UserContext.getEmployee();
        if(employee.isAdmin()){
            return true;
        }
        //2 拿到当前要调用的路径的注解,空的话放行
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        RequiresPermissions methodAnnotation = handlerMethod.getMethodAnnotation(RequiresPermissions.class);
        if(methodAnnotation == null){
            return true;
        }

        //3 拿到session中的表达式,如果包含就放行
        //List<String> expressions = (List<String>) request.getSession().getAttribute("EXPRESSIONS_IN_SESSION");
        List<String> expressions = UserContext.getExpressions();
        //拿到当前方法上的注解
        String[] value = methodAnnotation.value();
        if(expressions.contains(value[1])){
            return true;
        }
            request.getRequestDispatcher("/WEB-INF/views/common/nopermission.jsp").forward(request,response);
            return false;
    }
}
